<?php
class Mageex_ReviewRemender_Model_ProcessData extends Mage_Core_Model_Abstract
{
	
	public function sendMail()
	{
		$templateId = 1;
 
		// Set sender information
		$senderName 	= Mage::getStoreConfig('reviewremender/email/sendername');
		$senderEmail 	= Mage::getStoreConfig('reviewremender/email/senderemail');
		
		// Get Store ID
		$storeId = Mage::app()->getStore()->getId();       
		$infoOrder = $this->getInfoOrder();
		
		
		
		$template = Mage::getModel('core/email_template');
		
		$template->setTemplateText(Mage::getStoreConfig('reviewremender/email/body'));
		$host = Mage::getStoreConfig('reviewremender/email/host');
		$subject = Mage::getStoreConfig('reviewremender/email/subject');
		foreach ( $infoOrder as $order ) {
			
			$vars = array();
			$reception = array();
			$reception['fromemail']  = $senderEmail;
			$reception['fromname']   = $senderName;
			$reception['toemail']  	 = $order['customerEmail'];
			$reception['toname'] 	 = $order['customerName'];
			$orderModel = Mage::getModel('sales/order')->load($order['orderid']);
			$vars['order'] = $orderModel;
			$template->setDesignConfig(array('area'=>'frontend', 'store'=>$orderModel->getStoreId()));
			Varien_Profiler::start("email_template_proccessing");
			
			$templateProcessed = $template->getProcessedTemplate($vars, true);

			
			Varien_Profiler::stop("email_template_proccessing");
			$templateProcessed = str_replace('{{list_product}}', $this->getHtmlListProduct($order['productid']), $templateProcessed);
			Mage::helper('reviewremender')->sendMail($host,$subject, $templateProcessed, $reception);
		}
		return true;
	}
	public function getHtmlListProduct($arrProduct)
	{
		$strHtml = '<ul>';
		foreach ( $arrProduct as $key=>$id ) {
			$product = Mage::getModel('catalog/product')->load($id);
			$strHtml .= '<li><a href="'.Mage::getUrl('review/product/list', array('id'=> $id)).'">'.$product->getName().'</a></li>';
		}
		$strHtml .= '</ul>';
		return $strHtml;
	}
	public function getInfoOrder()
	{
		$arrInfo = array();
    	$orderCollection = Mage::getModel('sales/order')->getCollection();
		
		foreach ( $orderCollection as $orders ) {
			
			$order 	= Mage::getModel('sales/order')->load($orders->getId());
			$data 	= $order->getData();
			
			$items = $order->getAllItems();
			$orderDate = $order->getCreatedAt();
			$orderTimeStamp = Mage::helper('reviewremender')->getDateCount($orderDate);
			$timeStampNow = strtotime(date('d-m-Y'));
			if($timeStampNow>=$orderTimeStamp){
				$info = array();
				$info['orderid'] = $order->getId();
				$info['customerName'] = $order->getCustomerName();
				$info['customerEmail'] = $order->getCustomerEmail();
				$info['orderDate'] = $orderDate;
				foreach ($items as $itemId => $item)
				{
					$info['productid'][] = $item->getProductId();
				}
				$arrInfo[] = $info;	
			}
		}
		return $arrInfo;
	}
}